package fourfaith.com.ff_sl21_app.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;
import lecho.lib.hellocharts.formatter.SimpleLineChartValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ReportDetailFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ReportDetailFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ReportDetailFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private LineChartView mChartView;
    private  ArrayList<PointValue> values = new ArrayList<PointValue>();
    private ArrayList<Line> lines;
    private static SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private TextView time,currToday,currMonth;
    private LinearLayoutManager mLayoutManager;
    private static LinearLayout load_layout;
    private LinearLayout progressBar, listLayout, dataError, dataEmpty;
    private LinearLayout progressBarChar,chartLayout,dataErrorChar, dataEmptyChar;
    private DetailAdapter dAdapter;
    private  List<Map<String, Object>> data = new ArrayList<>();
    private static View view;
    private String stcd;
    private String flag;
    private float minY = 1f;//Y轴坐标最小值
    private float maxY = 100f;//Y轴坐标最大值
    private int totalDays = 24;//总共有多少天的数据显示

    private OnFragmentInteractionListener mListener;

    public ReportDetailFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ReportDetailFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ReportDetailFragment newInstance(String param1, String param2) {
        ReportDetailFragment fragment = new ReportDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_report_detail, container, false);
        if (getArguments() != null) {
            this.stcd = getArguments().getString("stcd");
            this.flag = getArguments().getString("flag");
        }
        this.view = view;
        initView(view);
        //swipeRefreshLayout.setRefreshing(true);
  /*      if (null == view) {
            view = inflater.inflate(getContentLayout(), container, false);
            if (getArguments() != null) {
                this.stcd = getArguments().getString("stcd");
                this.flag = getArguments().getString("flag");
            }
            this.view = view;
            initView(view);
        }*/
        return view;
    }
    public void initView(View view){
        cleanData();
        time = (TextView)view.findViewById(R.id.time);
        currToday = (TextView)view.findViewById(R.id.currToday);
        currMonth = (TextView)view.findViewById(R.id.currMonth);
        mChartView = (LineChartView)view.findViewById(R.id.chart);
        progressBar = (LinearLayout) view.findViewById(R.id.progressBar);
        listLayout = (LinearLayout) view.findViewById(R.id.listLayout);
        dataError = (LinearLayout) view.findViewById(R.id.dataError);
        dataEmpty = (LinearLayout) view.findViewById(R.id.dataEmpty);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        progressBarChar = (LinearLayout)view.findViewById(R.id.progressBarChar);
        dataErrorChar = (LinearLayout)view.findViewById(R.id.dataErrorChar);
        dataEmptyChar = (LinearLayout)view.findViewById(R.id.dataEmptyChar);
        chartLayout = (LinearLayout)view.findViewById(R.id.chartLayout);


        dAdapter = new DetailAdapter();
        // RecyclerView的ListView模式
        mLayoutManager = new LinearLayoutManager(getActivity());
        // 设置RecyclerView属性为ListView
        recyclerView.setLayoutManager(mLayoutManager);
        // 加载适配器
        recyclerView.setAdapter(dAdapter);
        // 添加滑动监听
        //recyclerView.addOnScrollListener(mOnScrollListener);
        //下拉刷新
      //swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);

        // 设置刷新时动画的颜色，可以设置4个
      //  swipeRefreshLayout.setColorSchemeResources(R.color.blue);

       // swipeRefreshLayout.setOnRefreshListener(this);
        SimpleDateFormat sDateFormat  = new  SimpleDateFormat("yyyy-MM-dd");
        String  date =sDateFormat.format(new  java.util.Date());
        //date = "2017-08-12";
        time.setText(date);
        currToday.setTextColor(Color.BLUE);
        initReportData(date, date);
    }
    public void initReportData(String begintime,String endtime){
        String userId = Constants.getUserId();
        String url = Constants.reportList +"?userId=" + userId + "&stcd="+stcd+"&flag="+flag+"&begintime="+begintime+"&endtime="+endtime;
        final SimpleDateFormat formats  = new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Calendar calendar = Calendar.getInstance();
        RequestQueue mQueue = RequestQueueSingleton.getInstance(getActivity()).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {
                        JSONArray dataArray =(JSONArray)responseResult.getData();
                        Map<String, Object> map;
                        if (dataArray != null && dataArray.size() > 0) {
                            //values = new ArrayList<PointValue>();//折线上的点
                            for (int i = 0; i < dataArray.size(); i++) {
                                JSONObject model = dataArray.getJSONObject(i);
                                String tm = model.getString("tm");
                                String value = model.getString("value");

                                map = new HashMap<>();
                                map.put("tm",tm);
                                map.put("value", value);
                                Date times  = null;
                                try {
                                    times = formats.parse(tm);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                calendar.setTime(times);
                                int monthDay = calendar.get(Calendar.HOUR_OF_DAY);
                                if(!value.equals("") && value!= null){
                                    values.add(new PointValue(monthDay, Float.parseFloat(model.getString("value"))));
                                }else{
                                    values.add(new PointValue(monthDay, 0));
                                }

                                data.add(map);
                            }
                        }
                        initLineData();
                        if (data == null || data.size() == 0) {
                            showEmptyPage();
                        } else {
                            showDataPage();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error.networkResponse == null) {
                    Toast.makeText(getActivity(), "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(getActivity(), "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);
    }

    public void initLineData(){
        //初始化折线上的点
/*        values = new ArrayList<PointValue>();//折线上的点
        values.add(new PointValue(10, Float.parseFloat("13.35")));
        values.add(new PointValue(11, Float.parseFloat("13.55")));
        values.add(new PointValue(12, Float.parseFloat("13.75")));

        values.add(new PointValue(13, Float.parseFloat("13.85")));
        values.add(new PointValue(14, Float.parseFloat("13.45")));
        values.add(new PointValue(15, Float.parseFloat("13.25")));
        values.add(new PointValue(16, Float.parseFloat("13.15")));*/

        //声明一条折线
        int lieColor=Color.parseColor("#94eafd");
        int pointColor=Color.parseColor("#94eafd");
        Line line = new Line(values).setColor(lieColor);//声明线并设置颜色
        //折线图上每个数据点的形状
        line.setShape(ValueShape.CIRCLE);
        line.setPointColor(pointColor);//点的颜色
        line.setHasPoints(true);//是否显示圆点
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
        line.setCubic(false);//设置是平滑的还是直的
        line.setFormatter(new SimpleLineChartValueFormatter(1));
        lines = new ArrayList<Line>();
        lines.add(line);

        //设置折线表相关属性和数据
        mChartView.setInteractive(true);//设置图表是可以交互的（拖拽，缩放等效果的前提）
        mChartView.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);//设置缩放方向
        mChartView.setMaxZoom((float) 3);//最大方法比例
        mChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);


        LineChartData datas = new LineChartData();
        Axis axisX = new Axis();//x轴
//        axisX.setName("时间");
        Axis axisY = new Axis();//y轴
//        axisY.setName("数值");
       // axisX.setMaxLabelChars(6);
        int gray = Color.parseColor("#045787");
        axisX.setTextColor(gray);
        axisX.setLineColor(gray);
        axisY.setTextColor(gray);
        axisY.setLineColor(gray);
        datas.setAxisXBottom(axisX);
        datas.setAxisYLeft(axisY);
        datas.setLines(lines);
        mChartView.setLineChartData(datas);//给图表设置数据

       // Viewport v = new Viewport(mChartView.getMaximumViewport());

  /*      if(values!=null){
            int size = values.size();
            Viewport viewportMax =new Viewport(-0.7f, mChartView.getMaximumViewport().height()*1.25f, size, 0);
            //   mChartView.setMaximumViewport(viewportMax);
            Viewport viewport =new Viewport(0,  mChartView.getMaximumViewport().height()*1.25f, size > 8 ? 8 : size, 0);

                         mChartView.setCurrentViewport(viewport);
        }*/
    }


    public static void finishRefreshing() {
        swipeRefreshLayout.setRefreshing(false);
        if (load_layout != null) load_layout.setVisibility(View.GONE);
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    class DetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        // 设置底部布局
        private static final int TYPE_FOOTER = 0;
        // 设置默认布局
        private static final int TYPE_DEFAULT = 1;
        // 判断是不是最后一个item，默认是true
        private boolean mShowFooter = true;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_DEFAULT) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_report_detail_item, parent, false);
                MyViewHolder vh = new MyViewHolder(v);
                return vh;
            } else {
                // 实例化布局
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, null);

                // 代码实现加载布局
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                return new FooterViewHolder(view);
            }

        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            // 用来在运行时指出对象是某一个对象
            if (holder instanceof MyViewHolder) {
                Map<String, Object> item = data.get(position);
                if (item == null) {
                    return;
                }

                //数据填充
                ((MyViewHolder) holder).deviceCode.setText(stcd);
                ((MyViewHolder) holder).factorValue.setText(Constants.getString(item.get("value")));
                ((MyViewHolder) holder).tm.setText(Constants.getString(item.get("tm")));

            } else {
            /*    if(7==(getItemCount()-1)){
                    ((FooterViewHolder)holder).more_data_msg.setText("已加载全部内容");
                }else{
                    ((FooterViewHolder)holder).more_data_msg.setText("正在加载");
                }*/
            }
        }

        // 设置不同的item
        @Override
        public int getItemViewType(int position) {
            // 判断当前位置+1是不是等于数据总数（因为数组从0开始计数），是的就加载底部布局刷新，不是就加载默认布局
            if (position + 1 == getItemCount()) {
                return TYPE_FOOTER;
            } else {
                return TYPE_DEFAULT;
            }
        }

        @Override
        public int getItemCount() {
            // 判断是不是显示底部，是就返回1，不是返回0
            int begin = mShowFooter ? 1 : 0;
            // 没有数据的时候，直接返回begin
            if (data == null) {
                return begin;
            }
            // 因为底部布局要占一个位置，所以总数目要+1
            return data.size() + begin;

        }

        // 设置是否显示底部加载提示（将值传递给全局变量）
        public void isShowFooter(boolean showFooter) {
            this.mShowFooter = showFooter;
        }

        // 判断是否显示底部，数据来自全局变量
        public boolean isShowFooter() {
            return this.mShowFooter;
        }

        // 底部布局的ViewHolder
        public class FooterViewHolder extends RecyclerView.ViewHolder {
            TextView more_data_msg;

            public FooterViewHolder(View view) {
                super(view);
                more_data_msg = (TextView) view.findViewById(R.id.more_data_msg);

            }
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView deviceCode;
            TextView factorValue;
            TextView tm;

            public MyViewHolder(View view) {
                super(view);
                deviceCode = (TextView) view.findViewById(R.id.deviceCode);
                factorValue = (TextView) view.findViewById(R.id.factorValue);
                tm = (TextView) view.findViewById(R.id.tm);
            }
        }
    }

    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        //列表
        progressBar.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataError.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);

        //报表
        progressBarChar.setVisibility(View.GONE);
        chartLayout.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.VISIBLE);
        dataEmptyChar.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {
        //列表
        progressBar.setVisibility(View.VISIBLE);
        dataError.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);

        //报表
        progressBarChar.setVisibility(View.VISIBLE);
        dataErrorChar.setVisibility(View.GONE);
        dataEmptyChar.setVisibility(View.GONE);
        chartLayout.setVisibility(View.GONE);

    }

    /**
     * 数据页面
     */
    public void showDataPage() {
        //列表
        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);

        //报表
        progressBarChar.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.GONE);
        chartLayout.setVisibility(View.VISIBLE);
        dataEmptyChar.setVisibility(View.GONE);

    }

    /**
     * 空数据页面
     */
    public void showEmptyPage() {
        //列表
        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.VISIBLE);

        //报表
        progressBarChar.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.GONE);
        chartLayout.setVisibility(View.GONE);
        dataEmptyChar.setVisibility(View.VISIBLE);

    }


    public static void cleanData() {
        //pageStart = 0;
       // values.clear();
       // data.clear();
    }

}
